package com.ruoyi.carShopService.controller;

import com.ruoyi.carShopService.domain.ShopUserDto;
import com.ruoyi.carShopService.service.LoginService;
import com.ruoyi.carShopService.service.RegisterService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.domain.CarMerchant;
import com.ruoyi.system.api.domain.CarMerchantPrincipal;
import com.ruoyi.system.api.domain.CarMerchantVerification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author yang
 * @version 1.0
 * @data 2024/9/12 19:57
 */
@RestController
public class RegisterController{

    @Autowired
    private LoginService loginService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 生成注册短信
    @CrossOrigin
    @RequestMapping("/createRegisterSms")
    public Map createRegisterSms(@RequestParam("phoneNumber") String phone) {
        return loginService.createSms(phone);
    }

    // 注册
    @RequestMapping("/register")
    public AjaxResult register(@RequestBody ShopUserDto shopUserDto){
        // 获取电话号
        String phone = shopUserDto.getPhone();
        CarMerchantPrincipal shopUser = loginService.selectByPhoneNumber(phone);
        if (shopUser != null){
            return AjaxResult.error("该用户已存在");
        }
        String o = (String)redisTemplate.opsForValue().get(phone);
        if (o == null){
            return AjaxResult.error("验证码已过期");
        }
        if( !o.equals(shopUserDto.getPhoneNum())){
            return AjaxResult.error("验证码错误");
        }
        int result = registerService.register(shopUserDto);
        if(result == 1){
            redisTemplate.delete(phone);
        }
        return result == 1 ? AjaxResult.success("注册成功") : AjaxResult.error("注册失败");
        }

}
